import axios from 'axios'
import { Notification, MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken,removeToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import router from '@/router/index'


axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// create an axios instance
const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: process.env.VUE_APP_BASE_API,
    // 超时
    timeout: 10000
})

// request interceptor
service.interceptors.request.use(
    config => {
        // 是否需要设置 token
        const isToken = (config.headers || {}).isToken === false
        if (getToken() && !isToken) {
            config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        // get请求映射params参数
        if (config.method === 'get' && config.params) {
            let url = config.url + '?';
            for (const propName of Object.keys(config.params)) {
            const value = config.params[propName];
            var part = encodeURIComponent(propName) + "=";
            if (value !== null && typeof(value) !== "undefined") {
                if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && typeof (value[key]) !== 'undefined') {
                    let params = propName + '[' + key + ']';
                    let subPart = encodeURIComponent(params) + '=';
                    url += subPart + encodeURIComponent(value[key]) + '&';
                    }
                }
                } else {
                url += part + encodeURIComponent(value) + "&";
                }
            }
            }
            url = url.slice(0, -1);
            config.params = {};
            config.url = url;
        }
        return config
    },
    error => {
        console.log(error) 
        return Promise.reject(error)
    }
)

// response 拦截器
service.interceptors.response.use(
    response => {
    
        // 未设置状态码则默认成功状态
        const code = response.data.code || 200;
        // 获取错误信息
        const msg = errorCode[code] || response.data.msg || errorCode['default']

        if (code === 200) {
            return response.data
        } else if (code === 401) {
            removeToken()
            Message({
                message: msg,
                type: 'error'
            })
            return Promise.reject(new Error(msg))
        } else {
            Message({
                message: msg,
                type: 'error'
            })
            return Promise.reject(new Error(msg))
        }
    },
    error => {
        // 出现网络超时
        router.push('500')
        return Promise.reject(error)
    }
)

export default service
